<template>
  <div>
    <div class="box">
      <el-form>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="仓库">
              <div
                v-show="!requestParam.data.mergeWarehouse"
                style="margin-right: 5px"
              >
                <GoodsWarehouseSelect
                  ref="warehouseSelect"
                  @select="warehouseSelectSelect"
                />
              </div>
              <el-button
                @click="toSelectWarehouse()"
                :type="requestParam.data.mergeWarehouse ? 'success' : ''"
                >合并仓库统计</el-button
              >
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="商品">
              <el-input
                size="large"
                clearable
                placeholder="商品名称、货号、条形编码"
                v-model="requestParam.data.goodsSynthesis"
                @keyup.enter.native="getBodyData()"
              ></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="商品或单品">
              <el-radio-group
                v-model="requestParam.data.singleProduct"
                class="ml-4"
                @change="getBodyData()"
              >
                <el-radio :label="false" size="large">商品</el-radio>
                <el-radio :label="true" size="large">单品</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <!-- 查询 -->
          <el-col :span="6">
            <el-form-item>
              <el-button
                size="large"
                type="primary"
                @click.prevent="getBodyData()"
                >查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="box">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>仓库查询</span>
            <el-button
              type="primary"
              @click="getCalculateCost()"
              style="float: right"
              >统计</el-button
            >
          </div>
        </template>
        <el-table
          ref="table"
          @selection-change="selectionChange"
          :reserve-selection="true"
          v-loading="loading"
          element-loading-text="Loading..."
          :data="bodyData.content"
          style="width: 100%"
          row-key="id"
          max-height="500px"
        >
          <el-table-column type="selection" width="55" />

          <el-table-column prop="warehouse.name" label="仓库名称" />
          <el-table-column prop="goods.name" label="商品名称" />
          <!-- 展示图 -->
          <el-table-column prop="fileIdOfImgArr" label="展示图" width="120">
            <template #default="{ row }">
              <el-image
                v-if="
                  row.goods != null &&
                  row.goods.fileIdOfImgArr != null &&
                  row.goods.fileIdOfImgArr.length > 0
                "
                style="width: 100px; height: 100px"
                :src="$kt.file.visit(row.goods.fileIdOfImgArr[0])"
                fit="contain"
                :preview-src-list="
                  $kt.file.getPreviewSrcList(row.goods.fileIdOfImgArr)
                "
                :preview-teleported="true"
              ></el-image>
              <div v-else>无</div>
            </template>
          </el-table-column>

          <el-table-column prop="goods.numberStr" label="商品货号" />

          <el-table-column prop="stock" label="库存" />

          <!-- 分类 -->
          <el-table-column prop="goods.type" label="商品分类" width="180">
            <template #default="{ row }">
              <div
                v-if="
                  row.goods != null &&
                  row.goods.type != null &&
                  row.goods.type.name != null
                "
              >
                {{ goodsJs.getGoodsTypeFullName(row.goods.type) }}
              </div>
            </template>
          </el-table-column>

          <!-- 上级商品 -->
          <el-table-column prop="goods.parent" label="上级商品" width="180">
            <template #default="{ row }">
              <div
                v-if="row.goods && row.goods.parent && row.goods.parent.name"
              >
                {{ row.goods.parent.name }}
              </div>
              <div v-else>
                <el-tag type="info">单独商品</el-tag>
              </div>
            </template>
          </el-table-column>

          <!-- 商品零售价 -->
          <el-table-column
            prop="goods.retailPrice"
            label="商品零售价"
            width="120"
          >
            <template #default="{ row }">
              <div v-if="row.goods != null && row.goods.retailPrice != null">
                {{ "￥" }}{{ row.goods.retailPrice }}
              </div>
            </template>
          </el-table-column>

          <!-- 商品批发价 -->
          <el-table-column
            prop="goods.wholesalePrice"
            label="商品批发价"
            width="120"
          >
            <template #default="{ row }">
              <div v-if="row.goods != null && row.goods.wholesalePrice != null">
                {{ "￥" }}{{ row.goods.wholesalePrice }}
              </div>
            </template>
          </el-table-column>

          <!-- 商品采购价 -->
          <el-table-column
            prop="goods.purchasePrice"
            label="商品采购价"
            width="120"
          >
            <template #default="{ row }">
              <div v-if="row.goods != null && row.goods.purchasePrice != null">
                {{ "￥" }}{{ row.goods.purchasePrice }}
              </div>
            </template>
          </el-table-column>

          <!-- 条形码 -->
          <el-table-column prop="barCode" label="商品条形编码" width="200">
            <template #default="{ row }">
              <div
                v-if="
                  row.goods != null &&
                  row.goods.barCode != null &&
                  row.goods.barCode != ''
                "
                @click="openBarCode(row.goods)"
                style="text-align: center"
              >
                <div>
                  {{ row.goods.barCode }}
                </div>
                <div style="font-size: 10px">(点击查看条形码)</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column
            prop="gmtModified"
            label="最后一次修改时间"
            width="180"
          >
            <template #default="{ row }">
              {{ $kt.date.format(row.gmtModified, "yyyy-MM-dd hh:mm:ss") }}
            </template>
          </el-table-column>

          <el-table-column
            v-if="!mergeWarehouse && singleProduct"
            fixed="right"
            label=""
            width="120"
          >
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click.prevent="dialogOfCheck.open(scope.row.id)"
              >
                <el-icon> 盘点 </el-icon>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div style="position: relative; height: 30px">
          <el-pagination
            @current-change="pageChange"
            style="
              position: absolute;
              left: 50%;
              top: 10px;
              transform: translateX(-50%);
            "
            layout="prev, pager, next"
            :page-size="requestParam.pageSize"
            :current-page="requestParam.pageNumber"
            :total="bodyData.totalElements"
          />
        </div>
      </el-card>
    </div>

    <BarDialog ref="barDialog" />
    <DialogOfCheck ref="dialogOfCheck" @submit="getBodyData" />
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import $kt from "@/vueKantboot";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import BarDialog from "@/components/barDialog/barDialog.vue";
import goodsJs from "@/commonJs/goods/index.js";
import GoodsWarehouseSelect from "@/components/goodsWarehouseSelect/goodsWarehouseSelect.vue";
import DialogOfCheck from "./components/DialogOfCheck.vue";

let barDialog = ref();
let warehouseSelect = ref();
let dialogOfCheck = ref();

let warehouseList = ref([]);

// 请求参数
let requestParam = ref({
  data: {
    // 是否合并仓库统计
    mergeWarehouse: false, // 是否合并仓库统计
    singleProduct: true, // 是否单品
    warehouseIds: [], // 仓库id
    goodsSynthesis: "", // 商品名称、货号、条形编码
  },
  pageNumber: 1,
  pageSize: 30,
});

let mergeWarehouse = ref(false);
let singleProduct = ref(true);

let toSelectWarehouse = () => {
  requestParam.value.data.mergeWarehouse =
    !requestParam.value.data.mergeWarehouse;
  requestParam.value = JSON.parse(JSON.stringify(requestParam.value));
  getBodyData();
};

let openBarCode = (row: any) => {
  if (row.barCode == null || row.barCode == "") {
    ElMessage({
      message: "条形码为空",
      type: "error",
    });
    return false;
  }
  barDialog.value.open(row);
};

let getCalculateCost = () => {
  $kt.request
    .request({
      url: "/business-goods-web/admin/goodsWarehouseStock/calculateCost",
      method: "post",
    })
    .then((res) => {
      if (res.data.success) {
        var message = "<div>";
        // 每行需要有下划线
        message +=
          "<table style='border-bottom:1px solid #999;border-collapse: collapse;' border='1px'>";

        // message += "<tr style='border-bottom:1px solid #999'><td>仓库</td><td>成本</td><td>总库存</td></tr>";
        message +=
          "<tr style='border-bottom:1px solid #999'><td style='width:180px;text-align:center'>仓库</td><td style='width:180px;text-align:center'>成本</td><td style='width:180px;text-align:center'>总库存</td></tr>";

        for (let i = 0; i < res.data.data.list.length; i++) {
          let item = res.data.data.list[i];
          // message += "<tr style='border-bottom:1px solid #999'><td>" + item.warehouse.name + "</td><td>￥" + item.stockAmount + "</td><td>" + item.stockCount + "</td></tr>";
          // 每个td占用的宽度为150px，并且文字居中
          message +=
            "<tr style='border-bottom:1px solid #999'><td style='width:180px;text-align:center'>" +
            item.warehouse.name +
            "</td><td style='width:180px;text-align:left'>￥" +
            item.stockAmount +
            "</td><td style='width:180px;text-align:center'>" +
            item.stockCount +
            "</td></tr>";
        }

        message += "</table>";
        message +=
          "<div style='margin-top:10px'>仓库数：" +
          res.data.data.list.length +
          "，总库存：" +
          res.data.data.stockCount +
          "</div>";
        message +=
          "<div style='margin-top:10px'>总成本：￥" +
          res.data.data.stockAmount +
          "</div>";
        message += "</div>";

        ElNotification({
          title: "统计",
          dangerouslyUseHTMLString: true,
          message,
          duration: 0,
        });

        return false;
      }
      ElMessage({
        message: res.data.errMsg,
        type: "error",
      });
    });
};

let dialogOfSave = ref();

let table = ref();

let toSave = (param: any) => {
  dialogOfSave.value.open(param);
};

let isTop = ref(true);

let warehouseSelectSelect = (val: any) => {
  requestParam.value.data.warehouseIds = val;
  getBodyData();
};

let bodyData = ref({
  content: [
    {
      gmtCreate: null,
      gmtModified: null,
      goods: {
        barCode: null,
        brandId: null,
        children: [],
        code: null,
        descriptionJson: null,
        fileIdOfImgArrStr: null,
        gmtCreate: null,
        gmtModified: 1698664887040,
        id: 1,
        minOrder: null,
        name: "1号商品",
        numberStr: null,
        parentId: null,
        price: null,
        priority: null,
        purchasePrice: null,
        retailPrice: null,
        selectList: [
          {
            busGoodsAttrSelect: {
              attrId: 1,
              code: null,
              gmtCreate: null,
              gmtModified: null,
              id: 1,
              value: "sss",
            },
            gmtCreate: null,
            gmtModified: null,
            goodsId: 1,
            id: 1,
            selectId: 1,
          },
        ],
        stock: null,
        stockWarningLower: null,
        stockWarningUpper: null,
        type: null,
        typeId: null,
        unitId: null,
        wholesalePrice: null,
      },
      goodsId: 1,
      id: 1,
      stock: 100,
      warehouse: {
        empIdOfManager: null,
        empOfManager: null,
        gmtCreate: 1698739893796,
        gmtModified: 1698739893796,
        id: 477607904501765,
        name: "123123",
        remark: null,
        store: null,
        storeId: null,
      },
      warehouseId: 477607904501765,
    },
    {
      gmtCreate: null,
      gmtModified: null,
      goods: {
        barCode: null,
        brandId: null,
        children: [],
        code: null,
        descriptionJson: null,
        fileIdOfImgArrStr: null,
        gmtCreate: null,
        gmtModified: 1698664887040,
        id: 1,
        minOrder: null,
        name: "1号商品",
        numberStr: null,
        parentId: null,
        price: null,
        priority: null,
        purchasePrice: null,
        retailPrice: null,
        selectList: [
          {
            busGoodsAttrSelect: {
              attrId: 1,
              code: null,
              gmtCreate: null,
              gmtModified: null,
              id: 1,
              value: "sss",
            },
            gmtCreate: null,
            gmtModified: null,
            goodsId: 1,
            id: 1,
            selectId: 1,
          },
        ],
        stock: null,
        stockWarningLower: null,
        stockWarningUpper: null,
        type: null,
        typeId: null,
        unitId: null,
        wholesalePrice: null,
      },
      goodsId: 1,
      id: 2,
      stock: 99,
      warehouse: {
        empIdOfManager: null,
        empOfManager: null,
        gmtCreate: 1698739908505,
        gmtModified: 1698739908505,
        id: 477607964741637,
        name: "123123",
        remark: null,
        store: null,
        storeId: null,
      },
      warehouseId: 477607964741637,
    },
  ],
  number: 1,
  size: 100,
  totalElements: 2,
  totalPage: 1,
});

let selection = ref([]);

let selectionChange = (val: any) => {
  selection.value = val;
};

let toEdit = (param: any) => {
  dialogOfSave.value.open(param);
};

let pageChange = (val: any) => {
  requestParam.value.pageNumber = val;
  getBodyData();
};

let toAddChildren = (param: any) => {
  dialogOfSave.value.open({
    id: "",
    name: "",
    parentId: param.id,
    fileIdOfImg: "",
  });
};

let loading = ref(true);

let getBodyData = () => {
  loading.value = true;

  $kt.request
    .request({
      url: "/business-goods-web/admin/goodsWarehouseStock/getBodyData",
      method: "post",
      data: requestParam.value,
    })
    .then((res) => {
      if (res.data.success) {
        bodyData.value = res.data.data;
        mergeWarehouse.value = requestParam.value.data.mergeWarehouse;
        singleProduct.value = requestParam.value.data.singleProduct;
        // fileIdOfImgArr
        for (let i = 0; i < bodyData.value.content.length; i++) {
          let item = bodyData.value.content[i];
          if (item.goods == null) {
            continue;
          }
          item.goods.fileIdOfImgArr = [];
          if (
            item.goods.fileIdOfImgArrStr != null &&
            item.goods.fileIdOfImgArrStr.length > 0
          ) {
            item.goods.fileIdOfImgArr = JSON.parse(
              item.goods.fileIdOfImgArrStr
            );
          }
        }

        console.log(bodyData.value);
      }
      loading.value = false;
    })
    .catch((err) => {
      loading.value = false;
      ElMessage({
        type: "error",
        message: "请求超时 请检查您的网络",
      });
    });
};

getBodyData();

let removeBatch = () => {
  $kt.request
    .request({
      url: "/business-goods-web/admin/goodsWarehouseStock/removeBatch",
      method: "post",
      data: selection.value,
    })
    .then((res) => {
      if (res.data.success) {
        ElMessage({
          message: "删除成功",
          type: "success",
        });
        getBodyData();
        return false;
      }
      ElMessage({
        message: res.data.errMsg,
        type: "error",
      });
    });
};

let toRemoveBatch = () => {
  if (selection.value.length == 0) {
    ElMessage({
      message: "请选择要删除的数据",
      type: "error",
    });
    return false;
  }

  // 询问是否删除
  ElMessageBox.confirm("此操作将永久删除该文件, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      // 删除
      removeBatch();
    })
    .catch(() => {
      // 取消
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
</script>

<style lang="scss" scoped>
.box {
  padding: 20px 20px 0 20px;
}

.box-box {
  background-color: #fff;
  color: #fff;
  text-align: center;
  padding: 30px;
  border-radius: 5px;
}

.box-box:hover {
  // 变小
  transform: scale(0.95);
}

.box-box:active {
  // 变小
  transform: scale(0.9);
}
</style>
